﻿using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Web.Base.ActionFilters
{
    public abstract class SecurityAttribute : ActionFilterAttribute
    {
        private readonly string[] include;
        private readonly string[] exclude;
       
        protected SecurityAttribute(string include): this(include, string.Empty)
        {

        }
        protected SecurityAttribute(string include, string exclude)
        {
            this.include = string.IsNullOrEmpty(include) ? new string[0] : SplitString(include);
            this.exclude = string.IsNullOrEmpty(exclude) ? new string[0] : SplitString(exclude);
        }

        protected abstract bool AuthorizeCore(HttpContextBase httpContext);
        protected abstract void HandleUnauthorizedRequest(ActionExecutingContext filterContext);

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if ((include.Length > 0 || exclude.Length > 0) && AuthorizeCore(filterContext.HttpContext))
            {
                return;
            }
            HandleUnauthorizedRequest(filterContext);
        }

        internal static string[] SplitString(string original)
        {
            if (string.IsNullOrEmpty(original))
            {
                return new string[0];
            }

            var split = from piece in original.Split(',')
                        let trimmed = piece.Trim()
                        where !string.IsNullOrEmpty(trimmed)
                        select trimmed;
            return split.ToArray();
        }
    }
}